<template>
  <el-dialog title="添加角色" :visible.sync="dialogVisible" width="48%" @close='clear'>
    <el-form ref="formRef" :model="addForm" label-width="80px" :rules="formRules">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="addForm.roleName" clearable></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="addForm.roleDesc" clearable></el-input>
      </el-form-item>
    </el-form>
    <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  data: function () {
    return {
      // 控制表单显隐
      dialogVisible: false,
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      formRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 监听对话框关闭事件，清空历史痕迹
    clear: function () {
      this.$refs.formRef.resetFields()
    },
    // 点击确认，添加角色
    confirm: function () {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return
        const res = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 200) {
          this.$message.warning('添加角色失败')
        }
        this.$message.success('角色添加成功')
        this.$parent.getRoleList()
        this.dialogVisible = false
      })
    }
  }
}
</script>
